import { getUrlParamByKey } from 'vue-xiaobu-utils'
import { verifyOpenID } from '../api/api'
import ConfirmBox from '../components/confirm/ConfirmBox.js'

function wxLogin(isOutLogin = false) {
  if (window.location.href.includes('code') && !isOutLogin) {
    let code = getUrlParamByKey('code')
    // 本地code
    let wxCode = getWxCode()
    console.warn(code, wxCode, 'code~~~~~~~~~~~~~~~~')
    if (code !== wxCode) {
      window.localStorage.setItem('wxCode', code)
      // ajaxAsync('/wx/init', {
      //   CODE: code
      // }).then(res => {
      //   window.localStorage.setItem('wxCode', code)
      //   window.localStorage.setItem('XIAOBUSESSION', res.SESSION_ID)
      // })
    }
  } else {
    let url = encodeURIComponent(window.location.href)
    if (window.location.href.includes('code')) {
      // window.location.replace(window.location.href.split('?')[0])
      window.history.go(-(window.history.length - 1))
    } else {
      window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${window.wxOauthAppid}&redirect_uri=${url}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
    }
  }
}

// 获取本地code
function getWxCode() {
  let value = window.localStorage.getItem('wxCode')
  if (value) {
    console.log(value)
    return value
  } else {
    return ''
  }
}

/**
 * 校验用户session授权openid是否有效（有效延长至30天，无效提示账号异常）
 *
 * @param {*} that 调用组件对象
 * @param {*} successCallback 验证成功回调函数
 */
function verifyUserSession(that, successCallback) {
  console.log(that)
  console.log(successCallback)
  verifyOpenID().then(res => {
    console.log(res)
    if (successCallback) {
      successCallback()
    }
    // console.log('微信openid授权成功-success')
  }).catch(err => {
    // console.log('err====微信openid失败======>')
    if (err && (err.errCode === '403' || (err.error && err.error.data && err.error.data.RSPCD !== '000000'))) {
      ConfirmBox.show({
        title: '提示',
        message: '您的账号长时间未操作或在其他设备登录，请重试',
        confirmText: '退出登录',
        cancelText: null
      }).then(() => {
        console.log('退出登录~')
        localStorage.clear()
        that.$router.push({ name: 'loginIndex' })
        wxLogin(true)
      })
    }
  })
}

// 判断是否登录，如果未登录或被顶号则清除缓存
// getMessage().catch(err => {
//   console.error(err)
//   let code = err.error.response.status
//   if (code === 403) {
//     window.localStorage.setItem('XIAOBUUSERBEAN', '')
//   }
// })

export { wxLogin, verifyUserSession }
